<template>
  <div class="mesWorkCalendars">
    <div>
      <el-select
        filterable
        v-model="queryValue"
        :placeholder="$t('mesWorkCalendars.selectLine')"
        @change="getList()"
      >
        <el-option
          v-for="item in queryOptions"
          :key="item.modelingCode"
          :label="item.modelingName"
          :value="item.modelingCode"
        >
        </el-option>
      </el-select>
      <el-button type="primary" @click="handerCopy">{{
        $t("common.copy")
      }}</el-button>
    </div>
    <el-calendar v-model="dateValue">
      <template #dateCell="{ data, date }">
        <div @click="handerClick(data, date)" class="center-pack">
          <div class="header">
            <p class="date" :class="data.isSelected ? 'is-selected' : ''">
              {{ data.day.split("-").slice(2).join("-") }}
              {{ data.isSelected ? "✔️" : "" }}
            </p>

            <div v-if="list[data.day]">
              <el-tag
                class="left"
                type="warning"
                v-if="
                  (list[data.day].length > 0
                    ? list[data.day][0].dateType
                    : '9') == '0'
                "
                >{{ $t("mesWorkCalendars.workday") }}</el-tag
              >
              <el-tag
                class="left"
                type="success"
                v-if="
                  (list[data.day].length > 0
                    ? list[data.day][0].dateType
                    : '9') == '1'
                "
                >{{ $t("mesWorkCalendars.weekend") }}</el-tag
              >
              <el-tag
                class="left"
                type="danger"
                v-if="
                  (list[data.day].length > 0
                    ? list[data.day][0].dateType
                    : '9') == '2'
                "
                >{{ $t("mesWorkCalendars.holiday") }}</el-tag
              >
            </div>
          </div>

          <p
            class="content nowrap"
            :title="` ${ite.teamName}:(${ite.shiftName}${ite.startTime}-${ite.endTime})`"
            :key="i"
            v-for="(ite, i) in list[data.day]"
          >
            {{ ite.teamName }}:({{ ite.shiftName }}{{ ite.startTime }}-{{
              ite.endTime
            }})
          </p>
        </div>
      </template>
    </el-calendar>

    <!-- 弹框 -->
    <el-dialog
      ref="aaaa"
      :title="$t('mesWorkCalendars.shiftAllocation')"
      :visible.sync="dialogVisible"
      width="86%"
    >
      <div>
        <span>{{ $t("mesWorkCalendars.nodeConfiguration") }}</span>
        <el-select
          v-model="addValue"
          :placeholder="$t('mesWorkCalendars.selectNodeConfig')"
        >
          <el-option :label="$t('mesWorkCalendars.workday')" value="0">
          </el-option>
          <el-option :label="$t('mesWorkCalendars.weekend')" value="1">
          </el-option>
          <el-option :label="$t('mesWorkCalendars.holiday')" value="2">
          </el-option>
        </el-select>
      </div>
      <tableTransfer
        ref="tabletransfers"
        @getDateType="getDateType"
        @getInfoList="(data) => (infoList = data)"
        :linCode="this.queryValue"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">{{
          $t("common.cancel")
        }}</el-button>
        <el-button
          type="danger"
          v-if="infoList.length"
          @click="deleteMapping()"
          >{{ $t("common.delete") }}</el-button
        >
        <el-button type="primary" @click="rowBatchCreate()">{{
          $t("common.save")
        }}</el-button>
      </span></el-dialog
    >

    <!-- 抽屉 -->
    <ele-form-drawer
      :title="$t('common.copy')"
      class="dialog-pack"
      :visible.sync="drawer"
      :isLoading="isLoading"
      v-model="formDataDialog"
      v-bind="formDescDialog"
      :request-fn="handleSubmit"
    >
    </ele-form-drawer>
  </div>
</template>

<script>
import {
  rowBatchCreate,
  mainPageList,
  copy,
  deleteMapping,
  deleteByDate,
} from "@/api/configuration/mesWorkCalendars";
import { operateList, searchConfig, formDescDialog, rowConfig } from "./config";
import { getLineCodeList } from "@/api/configuration/mesGate";
import tableTransfer from "./components/tableTransfer/index.vue";
import dayjs from "dayjs";
export default {
  name: "mesWorkCalendars",
  components: { tableTransfer },
  data() {
    return {
      dateValue: "", //当前日期
      queryValue: "", //查询条件
      queryOptions: [],
      isLoading: false,
      addValue: "", //节点配置：
      formDataDialog: {},
      formDescDialog, //新增修改框
      list: [], //日历主数据
      dialogVisible: false, //弹窗

      drawer: false, //抽屉
      infoList: [], //已选列表
    };
  },

  methods: {
    async deleteMapping() {
      this.$confirm($i18n.t('common.deleteBatch',{name:$i18n.t('mesWorkCalendars.name')}), $i18n.t("common.tip"), {
        confirmButtonText: $i18n.t("common.submit"), // "确定",,
        cancelButtonText: $i18n.t("common.cancel"), // "取消",,
        type: "warning",
      })
        .then(async () => {
          let data = this.infoList.map((ite) => {
            return ite.id;
          });

          let res = await deleteMapping(data.join(","));

          this.getList();
          this.dialogVisible = false;
        })
        .catch(() => {});
    },

    // 获取节点配置
    getDateType(data) {
      this.addValue = data;
    },
    findRow(data, type) {
      let obj = this.list.find((ite) => ite.key == data.day) || { list: [] };

      if (type == 1) {
        if (obj.list.length > 0) {
          return obj.list[0].dateType;
        } else {
          return false;
        }
      } else {
        if (obj.list.length > 0) {
          return obj.list;
        } else {
          return [];
        }
      }
    },
    // 主页日历信息
    async getList() {
      let data = {
        lineCode: this.queryValue,
        workCalendarMonth: dayjs(this.dateValue).format("MM"),
        workCalendarYear: dayjs(this.dateValue).format("YYYY"),
      };
      let res = await mainPageList(data);
      // console.log(2323, res)

      this.list = res.data.result || [];
    },
    //新增修改
    async rowBatchCreate() {
      if (!this.addValue) {
        this.$message.warning(
          this.$t("mesWorkCalendars.selectNodeConfig")
        );
        return;
      }
      let list = this.$refs.tabletransfers.selectedStaffList;
      let options = this.$refs.tabletransfers.options;
      let num = [];

      let data = [];
      if (list.length > 0) {
        data = list.map((ite, index) => {
          if (!ite.teamId) {
            num.push(Number(index) + 1);
          }

          let team = options.find((it) => it.id == ite.teamId) || {
            teamName: "",
          };
          return {
            ...ite,
            workCalendarDate: dayjs(this.dateValue).format("YYYY-MM-DD"),
            dateType: this.addValue,
            shiftId: ite.id,
            lineCode: this.queryValue,
            teamName: team.teamName,
          };
        });
        data = data.map((item) => {
          delete item.id;
          return {
            ...item,
          };
        });
      } else {
        // this.$message.warning(this.$t("mesWorkCalendars.selectShift"));
        console.log({
          workCalendarDate: dayjs(this.dateValue).format("YYYY-MM-DD"),
          lineCode: this.queryValue,
        });
        await deleteByDate({
          workCalendarDate: dayjs(this.dateValue).format("YYYY-MM-DD"),
          lineCode: this.queryValue,
        });
        this.getList();
        this.dialogVisible = false;
        this.$message.success($i18n.t("common.saveSuccess"));
        return;
      }

      if (num.length > 0) {
        this.$message.warning(
          `${$i18n.t("mesWorkCalendars.msg1")}${num}${$i18n.t(
            "mesWorkCalendars.msg2"
          )}`
        );
        return;
      }
      let res = await rowBatchCreate(data);
      this.$message.success($i18n.t("common.saveSuccess"));
      this.getList();
      this.dialogVisible = false;
    },
    //日历点击
    handerClick(data, date) {
      console.log("日历点击", data, date);
      var oDate1 = dayjs(new Date(date)).format("YYYY-MM-DD");
      var oDate2 = dayjs(new Date()).format("YYYY-MM-DD");
      if (new Date(oDate1).getTime() < new Date(oDate2).getTime()) {
        this.$message.warning(this.$t("mesWorkCalendars.limitMsg"));
      } else {
        this.dialogVisible = true;
        this.formDataDialog = {};
        this.$nextTick(() => {
          this.$refs.tabletransfers.mesWorkCalendarsList({
            lineCode: this.queryValue,
            workCalendarDate: data.day,
          });
          this.$refs.tabletransfers.getTeamList(this.queryValue);
        });
      }
    },
    // 获取线体
    async getLineCodeList() {
      const params = {
        modelingCode: this.$store.getters.factoryCode,
        level: 5,
      };
      const list = await getLineCodeList(params);
      this.queryOptions = list.data.result;
      if (list.data.result.length > 0) {
        this.queryValue = list.data.result[0].modelingCode;
        this.getList();
      }
    },
    //复制
    handerCopy() {
      this.drawer = true;
    },
    doSubmit({ title, api, data }) {
      this.isLoading = true;
      console.log(data);
      api(data)
        .then((res) => {
          const message = res.data.message;
          this.$message.success(message || title);
          this.drawer = false;
          this.getList();
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    //弹框提交事件
    handleSubmit(data) {
      console.log(data);
      data.lineCode = this.queryValue;
      if (this.isLoading) return; // 判断状态
      const params = { title: $i18n.t("common.addSuccess"), api: copy, data };
      this.doSubmit(params);
    },
    disableFields(flag) {
      this.formDescDialog.disabled = flag;
      this.formDescDialog.isShowSubmitBtn = !flag;
    },
  },
  created() {
    this.getLineCodeList();
    this.dateValue = new Date(); //初始值
  },
  mounted() {
    this.$nextTick(() => {
      let prevBtn = document.querySelector(
        ".el-calendar__button-group .el-button-group>button:nth-child(1)"
      );
      prevBtn.addEventListener("click", () => {
        // 点击前一个月
        //console.log(111);
        this.getList();
      });
      let dayBtn = document.querySelector(
        ".el-calendar__button-group .el-button-group>button:nth-child(2)"
      );
      dayBtn.addEventListener("click", () => {
        // 点击今天
        //console.log(222);
        this.getList();
      });
      let nextBtn = document.querySelector(
        ".el-calendar__button-group .el-button-group>button:nth-child(3)"
      );
      nextBtn.addEventListener("click", () => {
        // 点击下一个月
        //console.log(333);
        this.getList();
      });
    });
  },
  updated() {
    //console.log(33, this.dateValue);
    //console.log(22, dayjs(this.dateValue).format("YYYY-MM-DD"));
  },
};
</script>
<style lang="scss" scoped>
.mesWorkCalendars {
  /deep/ .el-calendar-day {
    min-height: 110px;
    height: auto;
  }
  /deep/ .el-calendar__button-group {
    // display: none;
  }
  .center-pack {
    height: 100%;
    .is-selected {
      color: #1989fa;
    }
    .header {
      display: flex;
      width: 100%;
      justify-content: space-between;
      align-items: center;
      .date {
        font-weight: 600;
        font-size: 16px;
      }
      .left {
        // position: relative;
        // left: 0px;
        font-size: 12px;
      }
    }
    .nowrap {
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    .content {
      font-size: 10px;
    }
  }

  .transfer-pack {
    width: 100%;
  }
  .block {
    display: flex;
  }
}
</style>
